//
//  MTTagCollectionView.swift
//  MT
//
//  Created by M on 2020/1/5.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

@objc
protocol MTTagCollectionViewDelegate: NSObjectProtocol {
    @objc optional func tagCollectionViewShouldPushToEditTagController(_ collectionView: MTTagCollectionView)
    
    @objc optional func tagCollectionView(_ collectionView: MTTagCollectionView, didUpdateContentSize size: CGSize)
}

class MTTagCollectionView: UICollectionView {
    
    weak var interactionDelegate: MTTagCollectionViewDelegate?

    @objc
    enum ColorStyle: Int {
        case backgroundBlack
        case background0x161616
        
        var backgrounColor: UIColor {
            switch self {
            case .backgroundBlack:
                return .black
            case .background0x161616:
                return UIColor(hex: 0x161616)
            }
        }

    }
    var colorStyle: ColorStyle = .background0x161616 {
        didSet {
            backgroundColor = colorStyle.backgrounColor
            reloadData()
        }
    }
    
    var models: [MTTagModel]? {
        didSet {
            if let ms = models {
                selectedModels = ms.filter({ (m) -> Bool in
                    return m.tagged == 1
                })
            }
            reloadData()
        }
    }
    
    /// 已选模型
    var selectedModels: [MTTagModel] = []
    
    var flowLayout: MTTagFlowLayout

    init(frame: CGRect) {
        let flowLayout = MTTagFlowLayout()
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = 24
        flowLayout.minimumLineSpacing = 16
        flowLayout.itemLength = 30
        flowLayout.sectionInset = UIEdgeInsets(top: 20, left: 14, bottom: 0, right: 14)
        flowLayout.scrollDirection = .vertical
        self.flowLayout = flowLayout
        super.init(frame: frame, collectionViewLayout: flowLayout)
        self.flowLayout.delegate = self
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------------------------ 初始化 ----------------------------------------
extension MTTagCollectionView {
    
    private func setup() {
        delegate = self
        dataSource = self
        backgroundColor = UIColor.theme.background
        register(MTTagCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: MTTagCollectionViewCell.self))
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UICollectionViewDelegate ----------------------------------------
extension MTTagCollectionView: MTTagFlowLayoutDelegate {
    
    func tagFlowLayout(_ flowLayout: MTTagFlowLayout, didFinishUpdateContentSize size: CGSize) {
        if let delegate = interactionDelegate {
            delegate.tagCollectionView?(self, didUpdateContentSize: size)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let models = models else { return }
        
        if indexPath.item == models.count - 1 {
            if let delegate = interactionDelegate {
                delegate.tagCollectionViewShouldPushToEditTagController?(self)
            }
            return
        }
        
        
        let model = models[indexPath.item]
        if model.tagged == 0 {
            model.tagged = 1
            if !selectedModels.contains(where: { (m) -> Bool in
                return model.id == m.id
            }) {
                selectedModels.append(model)
            }
            
        } else {
            model.tagged = 0
            if let index = selectedModels.firstIndex(where: { (m) -> Bool in
                return model.id == m.id
            }) {
                selectedModels.remove(at: index)
            }
        }
        reloadItems(at: [indexPath])
    }
    
}

// MARK: ------------------------------------ UICollectionViewDataSource ----------------------------------------
extension MTTagCollectionView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        guard let models = models, let name = models[indexPath.item].name else { return .zero }
        let width = name.width(font: PingFangSCMediumFont(12), maxHeight: 26) + 20
        return CGSize(width: width, height: 26)
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MTTagCollectionViewCell.self), for: indexPath) as? MTTagCollectionViewCell else {
            return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MTTagCollectionViewCell.self), for: indexPath)
        }
        cell.colorStyle = colorStyle
        cell.model = models?[indexPath.item]
        return cell
    }
    
}

// MARK: ------------------------------------ UICollectionViewDelegateFlowLayout ----------------------------------------
//extension MTTagCollectionView: UICollectionViewDelegateFlowLayout {
//
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        guard let models = models, let name = models[indexPath.item].name else { return .zero }
//        let width = name.width(font: PingFangSCMediumFont(12), maxHeight: 26) + 20
//        return CGSize(width: width, height: 26)
//    }
//
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        return UIEdgeInsets(top: 24, left: 16, bottom: 10, right: 16)
//    }
//
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
//        return 24
//    }
//
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
//        return 16
//    }
//
//}
